
#include <stdio.h>
#include <png.h>

#include "tlg.h"
#include "tlg_png.h"

int tlg_to_png(tlg_t* tlg, const char* file_name)
{
	FILE *fp = fopen(file_name, "wb");

	png_structp png_ptr;
	png_infop info_ptr;

	if (!fp)
	{
		fprintf(stderr, "Open PNG %s error\n", file_name);
		return -1;
	}

	//png_ptr = png_create_write_struct("libfate/libtlgcpp", NULL, NULL, NULL);
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png_ptr)
	{
		fclose(fp);
		fprintf(stderr, "png_create_write_struct error\n");
		return -1;
	}

	info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr)
	{
		fclose(fp);
		return -1;
	}

	if (setjmp(png_jmpbuf(png_ptr)))
	{
		fclose(fp);
		return -1;
	}

	png_init_io(png_ptr, fp);

	if (setjmp(png_jmpbuf(png_ptr)))
	{
		fclose(fp);
		return -1;
	}

	if (tlg->colors == 3)
	{
	png_set_IHDR(png_ptr, info_ptr, tlg->width, tlg->height,
		8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
		PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
	}
	else if (tlg->colors == 4)
	{
	png_set_IHDR(png_ptr, info_ptr, tlg->width, tlg->height,
		8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE,
		PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
	}
	else
	{
		fclose(fp);
		fprintf(stderr, "TLG colors must be 3 or 4!\n");
		return -1;
	}


	png_bytepp image = new png_bytep[tlg->height];
	for (int i = 0; i < tlg->height; ++i)
	{
		image[i] = tlg->buffer+i*tlg->colors*tlg->width;
	}

	png_set_rows(png_ptr, info_ptr, image);
	png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_BGR, NULL);

	if (setjmp(png_jmpbuf(png_ptr)))
	{
		fclose(fp);
		delete[] image;
		return -1;
	}

	delete[] image;
	fclose(fp);

	return 0;
}

int tlg_file_to_png_file(const char* tlg_path, const char* png_path)
{
	tlg_t* tlg = read_tlg_file(tlg_path);
	if (!tlg)
	{
		fprintf(stderr, "read_tlg_file error\n");
		return -1;
	}
	if (tlg_to_png(tlg, png_path))
	{
		fprintf(stderr, "tlg_to_png error\n");
		delete_tlg(tlg);
		return -1;
	}
	delete_tlg(tlg);
	return 0;
}

